package com.tbit.uqbike.client.controller;

import com.tbit.common.constant.OperationPlatform;
import com.tbit.common.entity.UserOpLog;
import com.tbit.uqbike.client.business.user_op_log.service.UserOpLogService;
import com.tbit.uqbike.client.constant.ResponseCode;
import com.tbit.uqbike.client.constant.annotation.PreventDuplication;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.FeeAppeal;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.service.FeeAppealService;
import com.tbit.uqbike.client.service.TokenService;
import com.tbit.uqbike.client.util.Assert;
import com.tbit.uqbike.client.util.EmojiCheckUtil;
import com.tbit.uqbike.client.util.OutputUtil;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 费用申诉
 *
 * @author: ShiGuang
 * @create: 2021-12-13 11:53
 */
@RestController
@RequestMapping("/feeAppeal")
public class FeeAppealController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private FeeAppealService feeAppealService;
    @Autowired
    private UserOpLogService userOpLogService;

    /**
     * 新增费用申诉
     *
     * @param feeAppeal 费用申述实体类
     * @param token     令牌
     * @param response  响应
     * @ignoreParams request
     */
    @PreventDuplication(expireSeconds = 5)
    @RequestMapping("/add")
    public void add(FeeAppeal feeAppeal, String token, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        Assert.hasLength(feeAppeal.getOrderNO(), "-3064", "订单编号不能为空");
        try {
            // 包装对象
            User user = tokenService.getUser(token);
            feeAppeal.setAccountId(user.getAccountId());
            feeAppeal.setUserId(user.getUserId());
            EmojiCheckUtil.check(feeAppeal.getRemark());
            // 如果用户上传了图片
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            List<MultipartFile> list = new ArrayList<>();
            if (isMultipart) {
                // 得到所有的文件
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                // 获取multiRequest 中所有的文件名
                Iterator iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    list.add(file);
                }
            }
            feeAppealService.insert(feeAppeal, list);

            // 插入用户操作日志
            userOpLogService.insertSingle(UserOpLog.builder()
                    .accountId(user.getAccountId())
                    .opUser(user.getName())
                    .opUserPhone(user.getPhone())
                    .targetUser(user.getName())
                    .targetUserPhone(user.getPhone())
                    .operation("费用申诉")
                    .opPlatform(OperationPlatform.CLIENT.code)
                    .opTime(LocalDateTime.now())
                    .detail("骑行订单号: " + feeAppeal.getOrderNO())
                    .result(true)
                    .build());

            map.put(ResponseCode.RET, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 根据userId获取全部
     *
     * @param token    令牌
     * @param response 响应
     * @ignoreParams request
     */
    @RequestMapping("/getByUserId")
    public void getByUserId(String token, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        try {
            User user = tokenService.getUser(token);
            List<FeeAppeal> feeAppeals = feeAppealService.getByUserId(user.getUserId());

            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, feeAppeals);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 根据userId分页查询
     *
     * @param token    令牌
     * @param rowCount 每页大小
     * @param pageNO   页码数
     * @param response 响应
     * @ignoreParams request
     */
    @RequestMapping("/queryPage")
    public void queryPage(String token, Integer rowCount, Integer pageNO, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();

        try {
            User user = tokenService.getUser(token);
            // 分页查询默认值
            if (rowCount == null || rowCount < 1) {
                rowCount = 10;
            }
            if (pageNO == null || pageNO < 1) {
                pageNO = 1;
            }
            // 查询数据
            List<FeeAppeal> feeAppeals = feeAppealService.queryPage(user.getUserId(), rowCount, pageNO);
            Integer count = feeAppealService.queryCount(user.getUserId());
            // 放入参数
            map.put("total", count);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, feeAppeals);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 根据订单编号查询费用申诉信息
     *
     * @param orderNO  订单编号
     * @param response 响应
     * @ignoreParams request
     */
    @RequestMapping("/getByOrderNO")
    public void getByOrderNo(String token, String orderNO, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        try {
            Assert.hasLength(orderNO, "-3064", "订单编号不能为空");
            User user = tokenService.getUser(token);
            FeeAppeal feeAppeal = feeAppealService.getByOrderNo(orderNO, user.getUserId());

            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, feeAppeal);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 查看用户未读消息数
     *
     * @param token    令牌
     * @param response 响应
     * @ignoreParams request
     */
    @RequestMapping("/getNotRead")
    public void getNotRead(String token, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        try {
            User user = tokenService.getUser(token);
            Integer count = feeAppealService.getNotRead(user.getUserId());

            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, count);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 已读消息
     *
     * @param token    令牌
     * @param orderNO  订单编号
     * @param response 响应
     * @ignoreParams request
     */
    @RequestMapping("/edit")
    public void edit(String token, String orderNO, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        try {
            User user = tokenService.getUser(token);
            feeAppealService.edit(orderNO, user.getUserId());
            map.put(ResponseCode.RET, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }
}